import store from '@/store/index'
import global from '@/config/global'
import baseUtil from '@/utils/baseUtil'

const uniRequest = {
	request(method, url, data = {}){
		return new Promise((resolve, reject) => {
			if(baseUtil.isBlank(url)){
				resolve({code:404, msg:'无效的请求地址'})
			}
			if(url[0] != '/') url = '//////' + url;
			let result = { code:1, msg:'请求失败' };
			uni.request({
				method: method || 'POST',
			    url: global.BASE_API+url, // 接口地址
				timeout: 1000 * 60,
			    data: data,
			    header: {
			        'wtoken': store.state.vuex_token || '' // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
			    },
				success: (res) => {
					console.log("success==>",res)
					// 判断res.statusCode == 200 为正常返回结果;暂不判断了,后台抛出异常为500,项目中通过判断data中的自定义code进行解析;
					// 返回结果集结构:
					// { 
					//   cookies: [],
					//   data: {code: 0, data: Array(6), msg: "成功"},
					//   errMsg: "request:ok",
					//   header: {Connection: "keep-alive", Transfer-Encoding: "chunked", Content-Type: "application/json;charset=UTF-8", Access-Control-Allow-Methods: "GET,POST,OPTIONS,PUT,DELETE", Access-Control-Max-Age: "2592000", …},
					//   statusCode: 200
					// }
					if(res.statusCode == 200){
						if(res.data.code == -1){
							store.dispatch('logout');
							uni.showToast({
								title:'请登录',
								icon: 'none'
							})
						}
						let data = res.data;
						if(!res.data.code){
							data.code = 200;
						}
						resolve(data);
					}else{
						//{ 
						//	error: "Not Found"
						//  message: "Not Found"
						//  path: "/weapp/api/dic/material/list/all"
						//  status: 404
						//  timestamp: 1578476107727
						// }
						if(res.data.code){
							resolve(res.data)
						}else{
							resolve({ code: res.statusCode || 1, msg: res.data.message || '请求失败' });
						}
					}
				},
				fail: (e) => {
					console.log("fail====>", e)
					// 目前只有地址错误,请求超时问题走fail,发现其他情况再来修改
					resolve({ code: 504, msg: '请求超时' })
				}
			});
		});
	},
	get(url, params){
		return this.request('GET', url, params)
	},
	put(url, params){
		return this.request('PUT', url, params)
	},
	post(url, data){
		return this.request('POST', url, data)
	},
	deleted(url, data){
		return this.request('DELETE', url, data)
	},
	/**
	 * 上传文件
	 * 将本地资源上传到服务器，客户端发起一个 POST 请求，其中 content-type 为 multipart/form-data。
	 * @param {data,okFn(task, res),progressFn(task, res)}
	  * data: 上传时携带的参数; okFn: 上传成功后的处理函数; progressFn: 监听商城进度的函数
	  * okFn与progressFn的参数说明
	  * task: 当前上传任务; res: 当前事件的结果集;
	 */
	uploadFile({data = {}, okFn, progressFn}){
		uni.chooseImage({
		    success: (chooseImageRes) => {
		        const tempFilePaths = chooseImageRes.tempFilePaths;
		        const uploadTask = uni.uploadFile({
		            url: global.UPLOAD_API, //上传接口地址
		            filePath: tempFilePaths[0],
		            name: 'file',
		            formData: data,
		            success: (uploadFileRes) => {
		                console.log(uploadFileRes.data);
						if(okFn){
							okFn(uploadTask, uploadFileRes)
						}
		            }
		        });
				
				// 如果需要监听上传进度
				if(progressFn){
					uploadTask.onProgressUpdate((progressUpdateRes) => {
						progressFn(uploadTask, progressUpdateRes);
						console.log('上传进度' + progressUpdateRes.progress);
						console.log('已经上传的数据长度' + progressUpdateRes.totalBytesSent);
						console.log('预期需要上传的数据总长度' + progressUpdateRes.totalBytesExpectedToSend);
					});
				}
		    }
		});
	}
} 

export default uniRequest;
